package su.jet.irc.client.service;

import java.io.BufferedReader;
import java.io.IOException;

import su.jet.common.irc.domain.User;
import su.jet.common.irc.protocol.Answer;
import su.jet.common.irc.protocol.Session;
import su.jet.common.irc.protocol.request.AuthRequest;

public class Authenticator {
	private BufferedReader input;
	private User user;
	private Session connectionWithServer;
	private Session connectionWithReader;
	
	public Authenticator(Session connectionWithServer, Session connectionWithReader, BufferedReader input) {
		this.input = input;
		this.connectionWithServer = connectionWithServer;
		this.connectionWithReader = connectionWithReader;
	}

	public void getUserInfoFromConsole() {
		try {
			System.out.println("Enter username:");
			String userName;
			userName = input.readLine().trim();
			System.out.println("Enter password:");
			String password = input.readLine().trim();
			user = new User(userName, password);
		} catch (IOException e) {
			System.out.println("Text input error. Restart and try again!");
			e.printStackTrace();
		}
	}
	
	public boolean authentificate() {
		AuthRequest authRequest = new AuthRequest(user);
		try {
			connectionWithServer.sendRequest(authRequest);
		} catch (Exception e) {
			System.out.println("Connection with server failed!");
		}
		try {
			Answer answer = connectionWithServer.recieveAnswer();
			if (answer.isConfirmed()) {
				connectionWithReader.sendObject("Authentification OK");
				return true;
			}
			else {
				connectionWithReader.sendObject("Authentification error");
				return false;
			} 
		} catch (IOException e) {
			System.out.println("Connection with reader console failed!");
			//e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("Data transport internal error");
			//e.printStackTrace();
		}
		return false;
	}

	public User getUser() {
		return user;
	}
	
}
